package com.sam.gui.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.dejian.platform.R;
import com.sam.dejian.Const;
import com.sam.dialog.LoadingDialog;
import com.sam.ui.base.activity.BaseActivity;
import com.sam.utils.CacheActivityManager;
import com.sam.utils.T;
import com.sam.utils.system.statusbar.StatusBarUtil;
import com.sam.widget.HeaderTitleBar;
import com.sam.widget.pull_to_refresh.PullToRefreshWebView;

import java.util.Locale;

/**
 * 用于规范于约束其子Activity
 * @author txg
 * data 10/ 23
 */
public abstract class BaseWebActivity extends BaseActivity {
	protected HeaderTitleBar header;
	protected WebView webView;
	private PullToRefreshWebView mPullRefreshWebView;
    private LoadingDialog loadDlg;

	private String currentUrl = "index.php";

	@Override
	protected void onCreate(@Nullable Intent savedInstanceStateIntent) {
		setContentView(R.layout.activity_web_frame);
		CacheActivityManager.addActivity(this);
	}

	protected void setContentUrl(String requestUrl){
		String localString = getResources().getConfiguration().locale.toString();
		if(localString.equals("en")) currentUrl = Const.HTTP_HOST+requestUrl+"&lang=en";
		else if(localString.equals("zh_CN")) currentUrl = Const.HTTP_HOST+requestUrl+"&lang=cn";
		else currentUrl = Const.HTTP_HOST+requestUrl+"&lang=cn";
		webView.loadUrl(currentUrl);
	}
	public void switchLanguage(Locale locale) {
		Configuration config = getResources().getConfiguration();// 获得设置对象
		Resources resources = getResources();// 获得res资源对象
		DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
		config.locale = locale; // 简体中文
		resources.updateConfiguration(config, dm);
	}

	@JavascriptInterface
	public void quit(){
		CacheActivityManager.finishActivity();
	}

	/*** 全局-初始化*/
	protected void findView(){
		header = (HeaderTitleBar) findViewById(R.id.header_title_bar);
		mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.pull_webview);
		webView = mPullRefreshWebView.getRefreshableView();
	}

	protected void setPullRefreshEnable(boolean enable){
		mPullRefreshWebView.setPullToRefreshEnabled(enable);
	}

	 /** 全局-设置点击事件等*/
	 protected void initView() {
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		webView.getSettings().setDefaultTextEncodingName("utf-8");//设置字符编码
		webView.getSettings().setJavaScriptEnabled(true);
		//设置可以访问文件
		webView.getSettings().setAllowFileAccess(true);
		webView.addJavascriptInterface(this, "java");
		//设置Web视图
		webView.setWebViewClient(new MyWebViewClient());
		webView.setWebChromeClient(new MyWebChromeClient());
		if (Build.VERSION.SDK_INT <= 18) {
			webView.getSettings().setSavePassword(false);
		} else {
// 		do nothing. because as google mentioned in the documentation -
// 		"Saving passwords in WebView will not be supported in future versions"
		}


		WebSettings webseting = webView.getSettings();
		webseting.setDomStorageEnabled(true);
		webseting.setAppCacheMaxSize(1024*1024*10);//设置缓冲大小，我设的是10M
		String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		webseting.setAppCachePath(appCacheDir);
		webseting.setAllowFileAccess(true);
		webseting.setAppCacheEnabled(true);
		webseting.setCacheMode(WebSettings.LOAD_DEFAULT);

		webView.setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});

		header.setOnHeaderClickListener(new HeaderTitleBar.OnHeaderClickListener() {
			@Override
			public void onHeaderLeftViewClick() {
				finish();
			}

			@Override
			public void onHeaderCenterViewClick() {}

			@Override
			public void onHeaderRightViewClick() {
				onHeaderRightBtnClick();
			}
		});
	}


	@JavascriptInterface
	public void alert(String msg){
		T.showShort(this, msg);
	}


	protected void onHeaderRightBtnClick(){}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
			webView.goBack(); // goBack()表示返回WebView的上一页面
			return true;
		}
		return super.onKeyDown(keyCode,event);
	}

	private void showLoadingDialog() {
		if (loadDlg == null) {
			loadDlg = new LoadingDialog(this);
		}
		loadDlg.show();
	}

	private void closeLoadingDialog() {
		if (loadDlg != null && loadDlg.isShowing()) {
			loadDlg.dismiss();
		}
	}

	@JavascriptInterface
	protected void reload(){
		webView.loadUrl(currentUrl);
	}

	private class MyWebViewClient extends WebViewClient {

		@Override
		public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			//这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
			view.loadUrl("file:///android_asset/error.html ");
		}


		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			showLoadingDialog();
			return true;
		}
		@Override
		public void onPageFinished(WebView view,String url){
			closeLoadingDialog();
			String title=view.getTitle();
			if(title==null){
				title="";
			}
			header.setTitle(title);
			if(pageFinishedListener != null) pageFinishedListener.onPageFinished(view);
		}
	}
	private PageFinishedListener pageFinishedListener;
	public interface PageFinishedListener {
		void onPageFinished(WebView view);
	}
	protected void setPageFinishedListener(PageFinishedListener pageFinishedListener){
		this.pageFinishedListener = pageFinishedListener;
	}


	//Web视图
	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onReachedMaxAppCacheSize(long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater) {
//			super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
			quotaUpdater.updateQuota(requiredStorage * 2);
		}

		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
			builder.setTitle("系统提醒").setMessage(message).setPositiveButton("确定", null);
			// 不需要绑定按键事件
			// 屏蔽keycode等于84之类的按键
			builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
					return true;
				}
			});
			// 禁止响应按back键的事件
			builder.setCancelable(false);
			AlertDialog dialog = builder.create();
			dialog.show();
			result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
			return true;
			// return super.onJsAlert(view, url, message, result);
		}

		/**
		 * 覆盖默认的window.confirm展示界面，避免title里显示为“：来自file:////”
		 */
		public boolean onJsConfirm(WebView view, String url, String message,final JsResult result) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
			builder.setTitle("系统提醒").setMessage(message).setPositiveButton("确定",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int which) {
							result.confirm();
						}
					}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.cancel();
						}
					});
			builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					result.cancel();
				}
			});

			// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
			builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
					return true;
				}
			});
			// 禁止响应按back键的事件
			// builder.setCancelable(false);
			AlertDialog dialog = builder.create();
			dialog.show();
			return true;
			// return super.onJsConfirm(view, url, message, result);
		}
	}
}
